package com.lt.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * @Author :liteng
 * @Time : 2023-10-22 21:21
 */
public class JwtUtils {
    private static String signKey = "liteng";//签名
    private static Long expire = 7200000000L;//过期时间为2000小时

    /**
     * 生成jwt令牌
     *
     * @param claims claims对象
     * @return jwt字符串
     */
    public static String generateJwt(Map<String, Object> claims) {
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, signKey)//设置签名算法
                .setClaims(claims)//载荷
                .setExpiration(new Date(System.currentTimeMillis() + expire))//设置有效期
                .compact();
        return jwt;
    }

    /**
     * 解析jwt令牌
     *
     * @param jwt jwt字符串
     * @return claims对象
     */
    public static Claims parseJwt(String jwt) {
        return Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static Long getNumFromJwt(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
        return (Long) claims.get("num");

    }
}
